package com.ztf0337.mycurriculumdesign.ui.manager;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.Utils.Checker;
import com.ztf0337.mycurriculumdesign.Utils.GetUtils;
import com.ztf0337.mycurriculumdesign.Utils.TimeConverters;
import com.ztf0337.mycurriculumdesign.Utils.TransitionUtils;
import com.ztf0337.mycurriculumdesign.adapter.ParkLotAdapter;
import com.ztf0337.mycurriculumdesign.adapter.ParkingSpaceAdapter;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.RentedParkingSpace;
import com.ztf0337.mycurriculumdesign.service.ParkLotService;
import com.ztf0337.mycurriculumdesign.service.ParkingSpaceService;
import com.ztf0337.mycurriculumdesign.ui.activity.MyRentDetailActivity;
import com.ztf0337.mycurriculumdesign.ui.activity.OrderDetailActivity;

import java.io.File;
import java.util.List;
import java.util.Objects;

public class MParkLotDetailActivity extends AppCompatActivity {

    private ParkLotService parkLotService;
    private ParkingSpaceService parkingSpaceService;
    private RecyclerView rvParkingSpace;
    private ParkingSpaceAdapter parkingSpaceAdapter;
    private TextView tvParkNumber;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.m_activity_park_lot_detail);

        parkLotService = new ParkLotService(this);
        parkingSpaceService = new ParkingSpaceService(this);


        Intent intent = getIntent();
        Long id = intent.getLongExtra("id", -1L);
        ParkLot parkLot = parkLotService.getParkLotById(id);

        if (parkLot == null) {
            Toast.makeText(this, "系统错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        Log.d("测试",parkLot.getAvailableSpaces()+"--"+parkLot.getTotalSpaces());

        ImageView btnBack,img;
        TextView tvParkName,tvBusinessStatus,tvParkLotType,tvParkAddress,tvInformation,tvParkPhone;

        btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> {
            finish();
        });

        img = findViewById(R.id.imageView);
        File filesDir = this.getFilesDir();
        File imagesDir = new File(filesDir, "gate_images");
        String child = parkLot.getUrl();
        Log.d("文件测试", "获取到图片"+child);
        File targetImage = new File(imagesDir, child);
        if (targetImage.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(targetImage.getAbsolutePath());
            img.setImageBitmap(bitmap);
        } else {
            img.setImageResource(R.drawable.img_default_park_lot);
        }

        tvParkName = findViewById(R.id.tvParkName);
        tvParkName.setText(parkLot.getParkLotName());
        tvBusinessStatus = findViewById(R.id.tvBusinessStatus);
        if (parkLot.getStatus()) {
            tvBusinessStatus.setTextColor(Color.GREEN);
        } else {
            tvBusinessStatus.setTextColor(Color.RED);
        }
        tvBusinessStatus.setText(parkLot.getStatus() ? "营业中" : "停用中");
        tvParkLotType = findViewById(R.id.tvParkLotType);
        tvParkLotType.setText(parkLot.getType());
        tvParkNumber = findViewById(R.id.tvParkNumber);
        tvParkNumber.setText(parkLot.getAvailableSpaces() +"/" +parkLot.getTotalSpaces());
        tvParkAddress = findViewById(R.id.tvParkAddress);
        tvParkAddress.setText(parkLot.getLocal());
        tvInformation = findViewById(R.id.tvInformation);
        tvInformation.setText(parkLot.getInformation());
        tvParkPhone = findViewById(R.id.tvParkPhone);
        tvParkPhone.setText(parkLot.getPhone());


        ImageView ic_edit,ic_delete;
        ic_edit = findViewById(R.id.ic_edit);
        ic_delete = findViewById(R.id.ic_delete);

        ic_edit.setOnClickListener(v -> {
            Intent intent1 = new Intent(this, MUpdateParkLotActivity.class);
            intent1.putExtra("from",2);
            intent1.putExtra("id",id);
            this.startActivity(intent1);
        });

        ic_delete.setOnClickListener(v -> {
            AlertDialog dialogHolder = new AlertDialog.Builder(this)
                    .setTitle("确认删除")
                    .setPositiveButton("确认", (dialog, which) -> {
                        parkLotService.delete(parkLot);
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent(this, ManagerHomeActivity.class);
                        intent1.putExtra("open",1);
                        this.startActivity(intent1);
                        finish();
                    })
                    .setNegativeButton("取消", null)
                    .create();
            dialogHolder.show();
        });


        TextView notData = findViewById(R.id.notData);
        rvParkingSpace = findViewById(R.id.rvParkingSpaces);
        rvParkingSpace.setLayoutManager(new LinearLayoutManager(this));

        List<ParkingSpace> thatAllParkingSpace = parkingSpaceService.getParkingSpacesByParkLotId(id);
        parkingSpaceAdapter = new ParkingSpaceAdapter(thatAllParkingSpace);
        rvParkingSpace.setAdapter(parkingSpaceAdapter);
        parkingSpaceAdapter.setOnItemClickListener((parkingSpace) -> {
            addOrUpdateParkingSpace(parkingSpace.getId(),2);        //传车位id
            Log.d("管理","点击停车位id "+parkingSpace.getId());
        });
        if (!thatAllParkingSpace.isEmpty()) {
            notData.setVisibility(GONE);
        } else {
            notData.setVisibility(VISIBLE);
        }

        ImageView ic_delete1,ic_affirm,ic_cansel,ic_add;
        ic_add = findViewById(R.id.ic_add);
        ic_delete1 = findViewById(R.id.ic_delete1);
        ic_affirm = findViewById(R.id.ic_affirm);
        ic_affirm.setVisibility(GONE);
        ic_cansel = findViewById(R.id.ic_cansel);
        ic_cansel.setVisibility(GONE);

        ic_add.setOnClickListener(v -> {
            ic_affirm.setVisibility(GONE);
            ic_cansel.setVisibility(GONE);
            ic_delete1.setVisibility(VISIBLE);

            addOrUpdateParkingSpace(id,1);          //传停车场id
        });

        ic_delete1.setOnClickListener(v -> {
            ic_affirm.setVisibility(VISIBLE);
            ic_cansel.setVisibility(VISIBLE);
            ic_add.setVisibility(GONE);
            ic_delete1.setVisibility(GONE);
            parkingSpaceAdapter.setSelectionMode(true);
        });
        ic_cansel.setOnClickListener(v -> {
            ic_affirm.setVisibility(GONE);
            ic_cansel.setVisibility(GONE);
            ic_add.setVisibility(VISIBLE);
            ic_delete1.setVisibility(VISIBLE);
            parkingSpaceAdapter.setSelectionMode(false);
            parkingSpaceAdapter.clearSelect();
        });

        ic_affirm.setOnClickListener(v -> {
            ic_affirm.setVisibility(GONE);
            ic_cansel.setVisibility(GONE);
            ic_add.setVisibility(VISIBLE);
            ic_delete1.setVisibility(VISIBLE);
            parkingSpaceAdapter.setSelectionMode(false);
            ParkLot parkLotById = parkLotService.getParkLotById(id);
            List<ParkingSpace> selectPSsAndClear = parkingSpaceAdapter.getSelectPSsAndClear();
            for (ParkingSpace p : selectPSsAndClear) {
                parkingSpaceService.delete(p);
                parkingSpaceAdapter.removeItem(p);
                parkLotById.setTotalSpaces(parkLotById.getTotalSpaces()-1);
                Log.d("测试",parkLotById.getAvailableSpaces()+"-"+parkLotById.getTotalSpaces());
                if (p.getStatus()){
                    parkLotById.setAvailableSpaces(parkLotById.getAvailableSpaces()-1);
                }
                Log.d("删除","车位 "+p.getId());
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
            }
            parkLotService.update(parkLotById);
            tvParkNumber.setText(parkLotById.getAvailableSpaces()+"/"+parkLotById.getTotalSpaces());

        });
    }

    private void addOrUpdateParkingSpace(Long id,int type) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.m_dialog_input_space, null);
        EditText et_parking_space_number, et_location, et_price_per_hours;
        Switch switch_status;
        et_parking_space_number = dialogView.findViewById(R.id.et_parking_space_number);
        et_location = dialogView.findViewById(R.id.et_location);
        et_price_per_hours = dialogView.findViewById(R.id.et_price_per_hours);
        switch_status = dialogView.findViewById(R.id.switch_status);
        Spinner spinner = dialogView.findViewById(R.id.spinner_type);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{"小型电动车", "中型电动车", "大型电动车", "小型燃油车", "中型燃油车", "大型燃油车"});
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("")
                .setView(dialogView)
                .setPositiveButton("确认", null)
                .setNegativeButton("取消", null)
                .create();

        if (type == 1) {

            dialog.setTitle("添加车位");
            dialog.setOnShowListener(dlg -> {
                        Button positiveBtn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                        positiveBtn.setOnClickListener(v -> {

                            String parking_space_number, location, price_per_hours, selectedType;
                            parking_space_number = et_parking_space_number.getText().toString().trim();
                            location = et_location.getText().toString().trim();
                            selectedType = spinner.getSelectedItem().toString();

                            if (parking_space_number.length() >= 5 || location.length() >= 10) {
                                Toast.makeText(this, "字数超出", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            price_per_hours = et_price_per_hours.getText().toString().trim();
                            double pricePerHours = 0.0;
                            if (!price_per_hours.isEmpty()) {
                                try {
                                    pricePerHours = Double.parseDouble(price_per_hours);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                    Toast.makeText(this, "请输入合法的价格", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } else {
                                Toast.makeText(this, "价格不能为空", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            ParkingSpace p = new ParkingSpace();
                            p.setStatus(switch_status.isChecked());
                            p.setLocation(location);
                            p.setParkingSpaceNumber(parking_space_number);
                            p.setPricePerHours(pricePerHours);
                            p.setType(TransitionUtils.transParkType(selectedType));
                            p.setParkLotId(id);
                            long insert = parkingSpaceService.insert(p);

                            ParkingSpace parkingSpace = parkingSpaceService.getParkingSpaceById(insert);
                            parkingSpaceAdapter.addItem(parkingSpace);
                            ParkLot parkLotById = parkLotService.getParkLotById(id);
                            parkLotById.setTotalSpaces(parkLotById.getTotalSpaces()+1);
                            if (p.getStatus()){
                                parkLotById.setAvailableSpaces(parkLotById.getAvailableSpaces()+1);
                            }
                            parkLotService.update(parkLotById);
                            tvParkNumber.setText(parkLotById.getAvailableSpaces()+"/"+parkLotById.getTotalSpaces());
                            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();  // 所有验证通过后手动关闭对话框
                        });
                    });
        }

        if (type == 2) {
            ParkingSpace parkingSpace = parkingSpaceService.getParkingSpaceById(id);
            et_parking_space_number.setText(parkingSpace.getParkingSpaceNumber());
            et_location.setText(parkingSpace.getLocation());
            et_price_per_hours.setText(parkingSpace.getPricePerHours().toString());
            switch_status.setChecked(parkingSpace.getStatus());

            String target = TransitionUtils.transParkType(parkingSpace.getType());

            int position = adapter.getPosition(target);
            Log.d("管理", "修改类型 " + target + " index " + position);
            spinner.setSelection(position);

            dialog.setTitle("修改车位");
            dialog.setOnShowListener(dlg -> {
                Button positiveBtn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                positiveBtn.setOnClickListener(v -> {
                    String parking_space_number = et_parking_space_number.getText().toString().trim();
                    String location = et_location.getText().toString().trim();
                    String price_per_hours = et_price_per_hours.getText().toString().trim();
                    String selectedType = spinner.getSelectedItem().toString();

                    if (parking_space_number.length() >= 5 || location.length() >= 10) {
                        Toast.makeText(this, "字数超出", Toast.LENGTH_SHORT).show();
                        return;  // 不关闭对话框
                    }

                    if (price_per_hours.isEmpty()) {
                        Toast.makeText(this, "价格不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    double pricePerHours;
                    try {
                        pricePerHours = Double.parseDouble(price_per_hours);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "请输入合法的价格", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    parkingSpace.setStatus(switch_status.isChecked());
                    parkingSpace.setLocation(location);
                    parkingSpace.setParkingSpaceNumber(parking_space_number);
                    parkingSpace.setPricePerHours(pricePerHours);
                    parkingSpace.setType(TransitionUtils.transParkType(selectedType));

                    parkingSpaceService.update(parkingSpace);
                    parkingSpaceAdapter.updateItem(parkingSpace);
                    Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();  // 所有验证通过后手动关闭对话框
                });
            });
        }
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.drawable.rounded_dialog_bg);
        dialog.show();
    }
}
